<template>
  <div class="aurora-login">
    <!-- 动态极光背景层 -->
    <div class="bg">
      <div class="aurora">
        <span class="blob b1"></span>
        <span class="blob b2"></span>
        <span class="blob b3"></span>
        <span class="mesh"></span>
        <span class="stars"></span>
      </div>
    </div>

    <div class="content">
      <div class="brand">
        <img src="@/assets/logo.png" alt="Logo" class="logo" />
        <div class="brand-text">
          <h2>ERP管理系统</h2>
          <p>智能企业管理平台</p>
        </div>
      </div>

      <!-- 交互式卡片（视差倾斜 + 高光） -->
      <div
        class="card"
        ref="panelRef"
        :style="panelStyle"
        @mousemove="handleTilt"
        @mouseleave="resetTilt"
      >
        <div class="card-header">
          <h3>欢迎回来</h3>
          <p>请使用账号登录系统</p>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
              class="neo-input"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin"
              class="neo-input"
            />
          </el-form-item>

          <el-form-item>
            <div class="form-options">
              <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
              <el-link type="primary" :underline="false" @click="showForgotPassword" class="forgot-link">
                忘记密码？
              </el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="neo-btn"
              :loading="loading"
              @click="handleLogin"
              style="width: 100%"
            >
              <span v-if="!loading">登录</span>
              <span v-else>正在连接...</span>
            </el-button>
          </el-form-item>
        </el-form>

        <div class="card-footer">
          <p>默认账号：<strong>admin</strong> / <strong>123456</strong></p>
        </div>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <ForgotPasswordDialog
      v-model="forgotPasswordVisible"
      @success="handleResetSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import ForgotPasswordDialog from './components/ForgotPasswordDialog.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const emit = defineEmits(['login'])

const loginFormRef = ref()
const loading = ref(false)
const forgotPasswordVisible = ref(false)
const panelRef = ref(null)
const panelStyle = ref({})

const loginForm = reactive({
  username: 'admin',
  password: '123456',
  rememberMe: false
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    const response = await userStore.login(loginForm)

    if (response.code === 200) {
      ElMessage.success(response.msg || '登录成功')
      emit('login', response)
      
      const redirect = route.query.redirect
      if (redirect && redirect !== '/login') {
        router.push(decodeURIComponent(redirect))
      } else {
        router.push('/dashboard')
      }
    } else {
      ElMessage.error(response.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '网络请求失败，请重试')
  } finally {
    loading.value = false
  }
}

const showForgotPassword = () => {
  forgotPasswordVisible.value = true
}

const handleResetSuccess = () => {
  forgotPasswordVisible.value = false
}

// 视差倾斜与高光跟随
const handleTilt = (e) => {
  if (!panelRef.value) return
  const rect = panelRef.value.getBoundingClientRect()
  const cx = rect.left + rect.width / 2
  const cy = rect.top + rect.height / 2
  const dx = (e.clientX - cx) / rect.width // -0.5 ~ 0.5
  const dy = (e.clientY - cy) / rect.height // -0.5 ~ 0.5

  const rotateX = (-dy * 8).toFixed(2)
  const rotateY = (dx * 10).toFixed(2)
  panelStyle.value = {
    transform: `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`,
    '--mx': dx,
    '--my': dy
  }
}

const resetTilt = () => {
  panelStyle.value = {
    transform: 'perspective(1000px) rotateX(0deg) rotateY(0deg)',
    '--mx': 0,
    '--my': 0
  }
}

onMounted(() => {
  resetTilt()
})

onUnmounted(() => {
  // 无需额外清理，这里只用于确保初始态
})
</script>

<style scoped>
.aurora-login {
  position: relative;
  min-height: 100vh;
  overflow: hidden;
  display: grid;
  place-items: center;
  background: #0b1220;
}

.bg {
  position: absolute;
  inset: 0;
}

.aurora {
  position: absolute;
  inset: 0;
  pointer-events: none;
}

.aurora .blob {
  position: absolute;
  width: 60vmax;
  height: 60vmax;
  filter: blur(60px) saturate(140%);
  opacity: 0.55;
  mix-blend-mode: screen;
  animation: drift 18s ease-in-out infinite;
}

.aurora .b1 {
  top: -20vmax;
  left: -10vmax;
  background: radial-gradient(closest-side, rgba(102,126,234,0.8), rgba(102,126,234,0.0));
}

.aurora .b2 {
  bottom: -25vmax;
  right: -15vmax;
  background: radial-gradient(closest-side, rgba(118,75,162,0.8), rgba(118,75,162,0.0));
  animation-delay: 4s;
}

.aurora .b3 {
  top: 10vmax;
  right: -20vmax;
  background: radial-gradient(closest-side, rgba(79,172,254,0.8), rgba(79,172,254,0.0));
  animation-delay: 8s;
}

.aurora .mesh {
  position: absolute;
  inset: -20vmax;
  background: conic-gradient(from 180deg at 50% 50%, #0b1220, rgba(102,126,234,0.12), rgba(118,75,162,0.12), rgba(79,172,254,0.12), #0b1220);
  filter: blur(60px) saturate(120%);
  opacity: 0.6;
  animation: hue 20s linear infinite;
}

.aurora .stars {
  position: absolute;
  inset: 0;
  background-image: radial-gradient(#ffffff11 1px, transparent 1px);
  background-size: 4px 4px;
  opacity: 0.4;
  transform: translate3d(0,0,0);
  animation: twinkle 12s linear infinite;
}

@keyframes drift {
  0%, 100% { transform: translate(0,0) scale(1); }
  50% { transform: translate(8vmax,-6vmax) scale(1.08); }
}

@keyframes hue {
  0% { filter: blur(60px) saturate(120%) hue-rotate(0deg); }
  100% { filter: blur(60px) saturate(120%) hue-rotate(360deg); }
}

@keyframes twinkle {
  0% { opacity: 0.35; transform: translateY(0); }
  50% { opacity: 0.55; transform: translateY(-2%); }
  100% { opacity: 0.35; transform: translateY(0); }
}

.content {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 460px;
  padding: 24px;
}

.brand {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  color: #e5ebff;
}

.brand .logo {
  height: 42px;
}

.brand-text h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
}

.brand-text p {
  margin: 2px 0 0;
  font-size: 13px;
  color: #a9b3d6;
}

.card {
  position: relative;
  border-radius: 18px;
  padding: 34px 32px 26px;
  background: rgba(16, 22, 35, 0.66);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.45);
  backdrop-filter: blur(16px) saturate(120%);
  transform-style: preserve-3d;
  transition: transform 0.2s ease;
}

.card::before {
  content: '';
  position: absolute;
  inset: -1px;
  border-radius: 18px;
  background: radial-gradient(40% 60% at calc(50% + (var(--mx, 0) * 20%)) calc(30% + (var(--my, 0) * 20%)), rgba(102,126,234,0.35), rgba(118,75,162,0.0));
  filter: blur(20px);
  opacity: 0.85;
  pointer-events: none;
}

.card-header {
  text-align: left;
  margin-bottom: 24px;
}

.card-header h3 {
  margin: 0 0 6px;
  font-size: 22px;
  font-weight: 800;
  color: #e5ebff;
}

.card-header p {
  margin: 0;
  color: #a9b3d6;
  font-size: 13px;
}

.login-form {
  margin-top: 12px;
}

.neo-input :deep(.el-input__wrapper) {
  border-radius: 10px;
  background: rgba(255,255,255,0.08);
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.05), 0 6px 20px rgba(0,0,0,0.25);
  transition: all 0.25s ease;
}

.neo-input :deep(.el-input__inner) {
  color: #e5ebff;
}

.neo-input :deep(.el-input__wrapper):hover {
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.08), 0 10px 26px rgba(102,126,234,0.35);
}

.neo-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.12), 0 14px 34px rgba(118,75,162,0.45);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  color: #a9b3d6;
}

.forgot-link {
  color: #b8c3ea;
}

.neo-btn {
  border-radius: 12px;
  font-weight: 700;
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 12px 28px rgba(102,126,234,0.45);
}

.neo-btn:hover {
  background: linear-gradient(135deg, #5a73db 0%, #6f3c99 100%);
  transform: translateY(-2px);
}

.card-footer {
  text-align: center;
  margin-top: 16px;
}

.card-footer p {
  margin: 0;
  color: #97a3c6;
  font-size: 12px;
}

@media (max-width: 480px) {
  .content { padding: 16px; }
  .card { padding: 26px 22px 22px; }
}
</style>

